package com.guazai.project.utils;

import cn.hutool.core.util.RandomUtil;
import com.guazai.project.constant.UserConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author guazai
 * @date 2024-08-21 20:55:42
 */
@Slf4j
@Component
public class EmailUtils {

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender javaMailSender;

    public String sendCodeEmail(String to) {
        if (StringUtils.isBlank(to)) {
            //throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱地址错误");
            return "";
        }

        //设置发件人
        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setFrom(from);
        //设置收件人
        mail.setTo(to);
        //生成随机验证码
        String code = RandomUtil.randomNumbers(UserConstant.VERIFICATION_CODE_LENGTH);
        //设置主题
        mail.setSubject("Api开放平台验证码");
        //生成发送内容
        mail.setText("验证码：" + code + "，该验证码十分钟内有效，如非本人操作请勿将验证码给与他人");
        //发送邮件
        javaMailSender.send(mail);
        return code;
    }
}
